﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;
using System.Xml.Linq;
using DocumentFormat.OpenXml.Packaging;

namespace Exentials.Xoox
{
    public class XDocumentBase<T> where T : OpenXmlPart
    {
        private XDocument _document;
        private T _openXmlPart;

        public event EventHandler Saving;

        public XDocumentBase(T part)
        {
            _openXmlPart = part;
            _document = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));
        }

        internal T DocumentPart
        {
            get
            {
                return _openXmlPart;
            }
        }

        internal XDocument Document
        {
            get
            {
                return _document;
            }
        }

        internal virtual void Save()
        {
            if (Saving != null) Saving.Invoke(this, EventArgs.Empty);
            using (XmlWriter writer = XmlWriter.Create(_openXmlPart.GetStream()))
            {
                _document.WriteTo(writer);
                writer.Flush();
                writer.Close();
            }
        }
    }
}
